package com.schoolhelper.login.service.impl;

import com.schoolhelper.login.domain.User;
import com.schoolhelper.login.mapper.UserMapper;
import com.schoolhelper.login.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserMapper userMapper;
    
    public String userRegiste(User user, String account) {
        // 检查账号是否已存在
        if (userMapper.findByAccount(account) != null) {
            return "account_exists";
        }
        
        // 设置默认值
        if (user.getUsername() == null) user.setUsername(user.getAccount());
        if (user.getRole() == null) user.setRole("student");
        if (user.getStatus() == null) user.setStatus("active");
        if (user.getCreateTime() == null) user.setCreateTime(LocalDate.now().toString());
        if (user.getUpdateTime() == null) user.setUpdateTime(LocalDate.now().toString());
        if (user.getBalance() == null) user.setBalance(new BigDecimal(0));
        
        // 执行插入操作
        try {
            int rows = userMapper.userRegiste(user);
            return rows > 0 ? "success" : "db_error";
        } catch (Exception e) {
            return "db_error";
        }
    }
    public User authenticate(String account, String password) {
        //验证用户名密码
//        System.out.println("account:"+account);
        User user = userMapper.findByAccount(account);
//        System.out.println("user:"+user);
        if (user != null && user.getPassword().equals(password)){
            // 更新最后登录时间
            userMapper.updateLastLoginTime(user.getId());
            return user;
        }else return null;
    }
    
    @Override
    public boolean updateUserProfile(User user) {
        try {
            // 设置更新时间
            user.setUpdateTime(LocalDate.now().toString());
            int rows = userMapper.updateUserProfile(user);
            return rows > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public User getUserById(Long userId) {
        try {
            return userMapper.findByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findByUsername(String username) {
        try {
            return userMapper.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}